import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import AdminUsers from '../components/power/AdminUsers'
import Rights from '../components/power/Rights'
import Roles from '../components/power/Roles'
import Faces from '../components/certify/Faces'
import Educations from '../components/certify/Educations'
import Occupations from '../components/certify/Occupations'
import Houses from '../components/certify/Houses'
import Users from '../components/user/User'

Vue.use(VueRouter)

const routes = [
  {
    path: '/', // 用户访问/, 重定向到登录
    redirect: '/login'
  },
  {
    path: '/login',
    // 要显示的组件
    component: Login
  },
  {
    path: '/home',
    component: Home,
    // 访问/home直接重定向到/welcome
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/admin/users',
        component: AdminUsers
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/faces',
        component: Faces
      },
      {
        path: '/educations',
        component: Educations
      },
      {
        path: '/occupations',
        component: Occupations
      },
      {
        path: '/houses',
        component: Houses
      },
      {
        path: '/users',
        component: Users
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 暴露路由之前, 先挂载路由守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from 代表从哪一个路径跳转古来
  // next是一个函数, 表示放行
  // next 放心 next('/login') 强制跳转
  // 如果用户访问的是登陆页, 直接放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = sessionStorage.getItem('token')
  // console.log('token值为: ', tokenStr)
  // token如果不存在, 强制跳转登录页
  if (!tokenStr) return next('/login')
  // 如果存在tokenStr字符串, 直接放行
  next()
})

export default router
